import { App, DirectiveBinding } from "vue";

function rightClickDirective(el: HTMLElement, binding: DirectiveBinding) {
    el.addEventListener("contextmenu", (event: MouseEvent) => {
        event.preventDefault(); // 阻止默认右键菜单

        const { value } = binding;
        console.log("自定义右键菜单binding", typeof value)
        if (typeof value === 'function') {
            value(event);
        } else if (typeof value === 'object' && value.fn && typeof value.fn === 'function') {
            value.fn(event, value.args, value.$index) // 传递自定义参数
        }
    });
}

export default {
    mounted(el: HTMLElement, binding: DirectiveBinding) {
        rightClickDirective(el, binding);
    },
    beforeUnmount(el: HTMLElement, binding: DirectiveBinding) {
        el.removeEventListener("contextmenu", binding.value);
    },
};

/**
 * 注册右键指令
 * @param app createApp实例
 * @param isDelGolbalRM 是否去掉全局右键菜单
 */
export function setupRightClickDirective(app: App, isDelGolbalRM: boolean): void {
    app.directive("right-click", {
        mounted: rightClickDirective,
        beforeUnmount: (el, binding) => {
            el.removeEventListener("contextmenu", binding.value);
        },
    });
    if (isDelGolbalRM) {
        removeGlobalRightMenu()
    }
}

export function removeGlobalRightMenu() {
    document.addEventListener("contextmenu", (e) => {
        e.preventDefault();
    });
}


import { useFolderStore } from "../store/folder";

export function customRightMenu() {
    document.addEventListener(
        "contextmenu",
        (e) => {
            e.preventDefault();
            const _target: any = e.target;

            if (_target) {
                const isGlobalArea = Array.from(_target.classList).includes(
                    "right-core-global"
                );
                const folderStore = useFolderStore();
                if (isGlobalArea) {
                    folderStore.showGlobalRightMenu = !folderStore.showGlobalRightMenu;
                    folderStore.rightMenuX = e.clientX;
                    folderStore.rightMenuY = e.clientY;
                }
            }
        },
        false
    );
}
